import http from './request';
let jweixin = require('./jweixin-module')

export default {
	isWechat: function() {
		var ua = window.navigator.userAgent.toLowerCase();
		if (ua.match(/micromessenger/i) == 'micromessenger') {
			return true;
		} else {
			return false;
		}
	},
	LoadWx: async function(options) {
		return new Promise((resolve, reject) => {
			if (this.isWechat()) {
				if (options.code) {
					uni.request({
						url: "http://59.110.46.120:8001/index.php/app/index/wx_callback",
						data: {
							code: options.code
						},
					}).then((res) => {
						let data = res[1].data;
						if (data.code === 20000) {
							uni.setStorageSync("WechatLogSuc", true)
							let user = data.data;
							uni.setStorageSync("userId", user.id)
							uni.setStorageSync('X-Token', user.third.token)
							uni.setStorageSync("username", user.user_login)
							uni.setStorageSync("userNickname", user.user_nickname)
							uni.setStorageSync("avatar", user.avatar)
							uni.setStorageSync("X-Device", "wx_official")

							uni.showToast({
								title: '微信登录成功',
							})
							resolve('suc');
						} else {
							uni.setStorageSync("WechatLogSuc", false)
							uni.showToast({
								title: '微信登录失败',
								icon: "error"
							})
							reject('err')
						}
					}).catch((msg) => {
						uni.setStorageSync("WechatLogSuc", false)
						reject('err:', msg)
					})
				} else {
					let state = encodeURIComponent(window.location.href);
					let link = "http://59.110.46.120:8001/index.php/app/index/wx_get_code";
					let appid = 'wx1a698f925577cb20';
					let uri = encodeURIComponent(link);
					let authURL =
						`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`;
					// alert(authURL);
					window.location.href = authURL;
				}
			}
		})
	}
}
